package com.link.base.wechat.wxlog.service;

import com.link.base.user.model.CoreUser;
import com.link.base.wechat.wxlog.dao.mybatis.mapper.WxLogMapper;
import com.link.base.wechat.wxlog.model.WxLog;
import com.link.base.wechat.wxlog.model.WxLogModule;
import com.link.core.basic.dao.KeyGenerateDao;
import com.link.core.basic.dao.mapper.BasicMapper;
import com.link.core.basic.service.BasicServiceImpl;
import com.link.core.basic.service.ServiceException;
import com.link.core.util.StringUtils;
import com.link.core.util.UserUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 微信日志服务 -- 记录微信接口、事件产生的日志
 *
 * @author ouyangzhenqiang
 * @date 2019/02/26
 */
@Service
public class WxLogServiceImpl extends BasicServiceImpl<WxLog> implements WxLogService {

    @Resource
    private WxLogMapper wxLogMapper;
    @Resource
    private KeyGenerateDao keyGenerateDao;

    @Override
    public BasicMapper<WxLog> getBasicMapper() {
        return wxLogMapper;
    }

    @Override
    public void log(WxLogModule module, String name, String details, String wxAppId, Long corpId) {
        WxLog wxLog = checkData(module, name, details, wxAppId, corpId);
        wxLog.setLevel("INFO");
        wxLogMapper.logInsertByInterface(wxLog);
    }

    @Override
    public void error(WxLogModule module, String name, String details, String wxAppId, Long corpId) {
        WxLog wxLog = checkData(module, name, details, wxAppId, corpId);
        wxLog.setLevel("ERROR");
        wxLogMapper.logInsertByInterface(wxLog);
    }

    /**
     * 检查必输参数
     *
     * @author ouyangzhenqiang
     * @date 2019/02/26
     */
    private WxLog checkData(WxLogModule module, String name, String details, String wxAppId, Long corpId) {
        String moduleStr = module.toString();
        if (StringUtils.isBlank(moduleStr)) {
            throw new ServiceException("WXLOG-001");
        }
        if (StringUtils.isBlank(name)) {
            throw new ServiceException("WXLOG-002");
        }
        if (StringUtils.isBlank(details)) {
            throw new ServiceException("WXLOG-003");
        }
        if (StringUtils.isBlank(wxAppId)) {
            throw new ServiceException("WXLOG-004");
        }
        CoreUser user = UserUtil.getUser();
        String userName = user != null ? user.getUsername() : "admin";
        if (corpId != null) {
            corpId = user != null ? user.getCorpid() : 0L;
        }
        WxLog wxLog = new WxLog();
        wxLog.setId(keyGenerateDao.keyGenerate());
        wxLog.interfaceCreateData(0L, 0L, corpId);
        wxLog.setUsername(userName);
        wxLog.setModule(moduleStr);
        wxLog.setName(name);
        wxLog.setDetails(details);
        wxLog.setWxAppId(wxAppId);
        return wxLog;
    }
}
